import API from '../../utils/api.js'
const app = getApp()

Page({
  data: {
    turnBack: 'back',
    cammerHeight: 300,
    isShowCammer: true,
    upPicList: [],
    file: "",
    //图片识别
    animation: 1,
    imgUrls: [
      // 'https://scxmcm.oss-cn-beijing.aliyuncs.com/1b47c04cd5dc6c62a041c02497d071bb.jpg',
      // 'https://scxmcm.oss-cn-beijing.aliyuncs.com/b83828410cf51a74e3c104cf21c4836b.jpg',
      // 'https://scxmcm.oss-cn-beijing.aliyuncs.com/5764bc7e3a95154544aa679598a50aae.jpg'
    ],
    navList: ['最新', '推荐', '附近'],
    num: 0,
    left: '14.5%',
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    showModal: false,
    questionList: [],
    hotList: [],
    scrollTop: 0,
    page: 1,
    type: 1,
    presentAddress: '', //当前城市
    more: '加载更多',
    showview: false,
    modalDlg: false,
    index: 0,
    idx: 0,
    currentItemId: 0
  },
  swiperChange: function (e) {
    var currentItemId = e.detail.current;
    this.setData({
      currentItemId: currentItemId
    })
  },
  enlarge: function(e) {
    var img = e.currentTarget.dataset.src;
    var imgarr = [];
    imgarr[0] = e.currentTarget.dataset.src;
    wx.previewImage({
      current: img,
      urls: imgarr,
    })
  },
  //分享
  share: function(res) {
    var index = res.currentTarget.dataset.index
    this.setData({
      showview: true,
      modalDlg: true,
      hasMask: true,
      index: index,
      idx: res.currentTarget.dataset.idx

    })
  },
  //取消分享
  shares() {
    this.setData({
      showview: false,
      modalDlg: false,
      hasMask: false
    })
  },
  preventTouchMove: function() {},
  //导航栏到顶部固定
  onPageScroll: function(e) { //监听页面滚动
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  //点击导航
  navTab(e) {
    var index = e.currentTarget.dataset.index
    var left = '14.5%'
    if (index == 0) {
      left = '14.5%',
        this.setData({
          page: 1,
          type: 1,
          questionList: [],
          more: '加载更多'
        })
      this.getQuestionList(1, 1)
    } else if (index == 1) {
      left = '47.5%',
        this.getQuestionList(1, 2)
      this.setData({
        page: 1,
        type: 2,
        questionList: [],
        more: '加载更多'
      })
    } else {
      left = '81.5%',
        this.setData({
          page: 1,
          type: 3,
          questionList: [],
          more: '加载更多'
        })
      this.getQuestionList(1, 3)
    }
    this.setData({
      num: index,
      left: left
    })
  },
  onLoad: function() {
    this.ctx = wx.createCameraContext()//图片识别
    var that = this;
    if (!wx.getStorageSync("userInfo")) {
      wx.navigateTo({
        url: '/pages/authorizationUserInfo/authorizationUserInfo?form=1'
      })
    } else {
      this.getBanner()
      that.getQuestionList(1, 1)
      that.hotSearchList()
      
    }
    
    that.getLocation()
  },
  upPic() {//图片识别
    var _this = this
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        _this.setData({
          tempFilePaths: tempFilePaths
        })
        for (var k in tempFilePaths) {
          _this.uploadFile(tempFilePaths[k])
        }
      }
    })
  },
  uploadFile(img) {
    console.log(img)
    var _this = this
    wx.showLoading({ title: '图片上传中...' })
    wx.uploadFile({
      url: 'https://www.szhongtu.net/mcbase/public/index.php/wxroutine/quanzi/upload',
      filePath: img,
      name: 'file',
      formData: {
        'user': 'test'
      },
      success(res) {
        wx.hideLoading()
        var data = JSON.parse(res.data)
        if (data.ret == 0) {
          _this.recognition(data.url)
        }
      }
    })
  },
  // 图像识别
  recognition(img) {
    var data = {
      imageurl: img,
    }
    API.recognition(data).then(res => {
      if (res.ret == 0) {
        console.log(res);
        // wx.showModal({
        //   title: '识别成功',
        //   content: res.data.result[0].name
        // })
        wx.setStorageSync('name', res.data.result[0].name);
        wx.setStorageSync('image_url', res.data.result[0].baike_info.image_url);
        wx.setStorageSync('description', res.data.result[0].baike_info.description);
        wx.navigateTo({
          url: '/pages/scan/scan'
        })
      } else {
        wx.showModal({
          title: '识别成功',
          content: res.data.result[0].name
        })
      }
    })
  },
  // 获取当前位置经维度
  getLocation() {
    var _this = this
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        _this.mapInfo(longitude, latitude)
      }
    })
  },
  mapInfo(longitude, latitude) {
    var _this = this
    console.log(location)
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=VT6BZ-C5LKP-5KLDX-VJFAK-7S326-AMBQO',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log('获取城市')
        console.log(res.data.result.address)
        wx.setStorageSync('lat', latitude)
        wx.setStorageSync('lon', longitude)
        wx.setStorageSync('address', res.data.result.address)
        _this.setData({
          presentAddress: res.data.result.address
        })
      }
    })
  },
  toHotSearch() {
    console.log('是否执行')
    wx.navigateTo({
      url: '/pages/hotsearch/hotsearch',
    })
  },
  toCammerPage() {
   this.upPic();
     return
    wx.navigateTo({
      url: '/pages/cammerTest/cammerTest',
    })
  },
  toDetail(e) {
    wx.navigateTo({
      url: '/pages/questionDetail/questionDetal?id=' + e.currentTarget.dataset.id,
    })
  },
  getBanner() {
    API.getIndexBanner().then(res => {
      console.log('获取首页banner');
      console.log(res.data)
      if (res.ret == 0) {
        this.setData({
          imgUrls: res.data
        })
      }
    })
  },
  //获取最新/推荐/附近数据
  getQuestionList(page, type) {
    var that = this;
    var data = { 
      page: page,
      limit: 10,
      type: type,
      latitude: wx.getStorageSync('lat'),
      longitude: wx.getStorageSync('lon')
    }
    API.answer(data).then(res => {
      setTimeout(function () {
        that.setData({
          animation: 2
        })
      }, 2000)
      console.log(res)
      var questionList = this.data.questionList
      if (res.ret == 0 && res.data.length > 0) {
        this.setData({
          questionList: questionList.concat(res.data),
          more: "加载更多"
        })
      } else {
        this.setData({
          more: "主人我是有底线的哟~"
        })
      }
    });

  },
  hotSearchList() {
    API.hotSearch().then(res => {
      console.log(res)
      if (res.ret == 0) {
        this.setData({
          hotList: res.data
        })
      }
    })
  },
  onReady: function() {

  },
  onShow: function() {
    wx.removeStorageSync('UpPic')
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
  
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var index = this.data.index;
    var idx = this.data.idx;
    console.log(this.data.questionList[1].title);
    console.log(this.data.questionList[1].images[0]);
    if (res.from == 'button') {
      if (res.target.id == 1) {
        return {
          title: this.data.questionList[idx].title,
          path: "pages/questionDetail/questionDetal?id=" + this.data.index,
          imageUrl: this.data.questionList[idx].images[0],
          success: function(res) {
            // 转发成功
            wx.showToast({
              title: "分享成功",
              icon: 'success',
              duration: 2000
            })
          },
          fail: function(res) {
            // 分享失败
          },
        }
      }
    } else {
      return {
        title: '点击右上角要分享的标题',
        path: '/pages/index/index',
        success: function(res) {

        }
      }
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var index = this.data.index;
    var idx = this.data.idx;
    console.log(this.data.questionList[1].title);
    console.log(this.data.questionList[1].images[0]);
    if (res.from == 'button') {
      if (res.target.id == 1) {
        return {
          title: this.data.questionList[idx].title,
          path: "pages/questionDetail/questionDetal?id=" + this.data.index,
          imageUrl: this.data.questionList[idx].images[0],
          success: function(res) {
            // 转发成功
            wx.showToast({
              title: "分享成功",
              icon: 'success',
              duration: 2000
            })
          },
          fail: function(res) {
            // 分享失败
          },
        }
      }
    } else {
      return {
        title: '点击右上角要分享的标题',
        path: '/pages/index/index',
        success: function(res) {

        }
      }
    }
  },
  //页面上拉加载
  onReachBottom: function() {
    console.log(this.data.type);
    if (this.data.type == 1) {
      var page = ++this.data.page;
      var type = this.data.type;
      this.getQuestionList(page, type)
    }
    if (this.data.type == 2) {
      var page = ++this.data.page;
      var type = this.data.type;
      this.getQuestionList(page, type)
    }
  }

})